package com.xiyou.week01.stack;

import java.util.Stack;

/**
 * 150. 逆波兰表达式求值
 *
 * @ClassName：LeetCode150
 * @Author：西柚
 * @Date：2021/11/22 11:13 上午
 * @Versiion：1.0
 */
public class EvalRPN {

    /**
     * 输入：tokens = ["4","13","5","/","+"]
     * 输出：6
     * 解释：该算式转化为常见的中缀算术表达式为：(4 + (13 / 5)) = 6
     *
     * @param tokens
     * @return
     */
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<Integer>();
        for (String token : tokens) {
            if ("+".equals(token)) {
                Integer y = stack.pop();
                stack.push(stack.pop() + y);
            } else if ("-".equals(token)) {
                Integer y = stack.pop();
                stack.push(stack.pop() - y);
            } else if ("*".equals(token)) {
                Integer y = stack.pop();
                stack.push(stack.pop() * y);
            } else if ("/".equals(token)) {
                Integer y = stack.pop();
                stack.push(stack.pop() / y);
            } else {
                stack.push(Integer.valueOf(token));
            }
        }
        return stack.pop();
    }

    public static void main(String[] args) {
        EvalRPN leetCode150 = new EvalRPN();

//        String[] tokens = new String[]{"3", "1", "+", "2", "*"};
        String[] tokens = new String[]{"4", "13", "5", "/", "+"};

        System.out.println(leetCode150.evalRPN(tokens));
    }
}
